package com.colabo.j2ee.web.core.persistence;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.ibatis.sqlmap.client.extensions.ParameterSetter;
import com.ibatis.sqlmap.client.extensions.ResultGetter;
import com.ibatis.sqlmap.client.extensions.TypeHandlerCallback;

public class Date2StringTypeHandlerCallback implements TypeHandlerCallback {
	public static final String DATA_TO_STRING_FORMATE = "yyyy-MM-dd HH:mm:ss";

	/**
	 * 把java.Util.Date转为字符型日期数据
	 * 
	 * @param d
	 *            java.Util.Date日期
	 * @param pattern
	 *            日期转换格式
	 * @return 字符型日期
	 */
	public static String formatDate(java.util.Date d, String pattern) {
		SimpleDateFormat formatter = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
		formatter.applyPattern(pattern);
		return formatter.format(d);
	}

	/**
	 * 把字符型日期数据转为java.Util.Date型
	 * 
	 * @param sDate
	 *            字符型日期
	 * @param sFmt
	 *            日期转换格式
	 * @return java.Util.Date
	 */
	public static java.util.Date toDate(String sDate, String sFmt) {
		SimpleDateFormat sdfFrom = null;
		java.util.Date dt = null;
		try {
			if (sDate == null) {
				return null;
			}
			sdfFrom = new SimpleDateFormat(sFmt);
			dt = sdfFrom.parse(sDate);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			sdfFrom = null;
		}

		return dt;
	}

	public Object getResult(ResultGetter arg0) throws SQLException {
		String s = arg0.getString();
		if (s != null) {
			return toDate(s, DATA_TO_STRING_FORMATE);
		}
		return null;
	}

	public void setParameter(ParameterSetter arg0, Object arg1) throws SQLException {
		Date date = (Date) arg1;
		arg0.setString(formatDate(date, DATA_TO_STRING_FORMATE));
	}

	public Object valueOf(String arg0) {
		return toDate(arg0, DATA_TO_STRING_FORMATE);
	}
}
